/*
 * Copyright 2011 Romain Gilles
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.jvdb;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.ArrayList;

/**
 * TODO_LIST:
 * - TODO: add connection id and statement identifier per connection id
 */
class StatementTimer extends AbstractTimer {

    static String STATEMENT_LOGGER_NAME = TIMER_LOGGER_NAME + ".stmt";
    private static final Logger logger = LoggerFactory.getLogger(STATEMENT_LOGGER_NAME);
    static final String STATEMENT_END = ";\n";
    private final List<String> batchedStatements = new ArrayList<String>();
    final String sql;

    StatementTimer(int connectionId, int statementId, String sql) {
        super(connectionId, statementId);
        this.sql = sql;
        addSql(sql);
    }

    static StatementTimer newStartedTimer(int connectionId, int statementId, String sql) {
        StatementTimer result = newTimer(connectionId, statementId, sql);
        result.start();
        return result;
    }

    static StatementTimer newTimer(int connectionId, int statementId, String sql) {
        return new StatementTimer(connectionId, statementId, sql);
    }

    @Override
    final String parseSql() {
        if (batchedStatements.size() > 1)
            return parseSql(batchedStatements);
        else {
            return parseSql(sql);
        }
    }

    String parseSql(String sql) {
        return sql;
    }
    String parseSql(List<String> statements) {
        return parseBatchedStatements(statements);
    }

    static String parseBatchedStatements(List<String> statements) {
        int size = statements.size();
        StringBuilder result = newStatementBuffer(size);
        for (String statement : statements) {
            result.append(statement).append(STATEMENT_END);
        }
        return result.toString();
    }

    static StringBuilder newStatementBuffer(int size) {
        return new StringBuilder(1024 * size);
    }

    public void addBatch(String sql) {
        addSql(sql);
    }

    private void addSql(String sql) {
        batchedStatements.add(sql);
    }
}

